package mtt.us.hmvcFramework.client.modul;

import mtt.us.hmvcFramework.client.hmvc.events.AddViewEvent;
import mtt.us.hmvcFramework.client.hmvc.events.RemoveViewEvent;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;

import hmvc4gwt.client.controller.Controller;
import hmvc4gwt.client.event.HmvcEvent;
import hmvc4gwt.client.event.HmvcEventListener;
import hmvc4gwt.client.triad.Triad;
import hmvc4gwt.client.view.View;

/**
 * Der ModulController ist für den Zugriff auf das RootPanel zuständig, er
 * Empfängt Add-, Remove-, Disable- und EnableViewEvent()'s. Er ausserdem
 * enthält eine Map mit allen im Moment angezeigten Views
 * 
 * @author jens.meiss
 * 
 */

public abstract class ModulController extends Controller implements EntryPoint, HmvcEventListener {

	public final void doInit() {
		/*
		 * Controller für das hinzufügen und entfernen von Views registrieren
		 */
		register(AddViewEvent.class, this);
		register(RemoveViewEvent.class, this);
		
		doInitImpl();
	}

	/**
	 * repräsentiert die Initializeable-Methode doInit()
	 */
	public abstract void doInitImpl();

	public final void handleEvent(HmvcEvent event) {
		
		if (event instanceof AddViewEvent) {
			AddViewEvent addViewEvent = (AddViewEvent) event;
			addView(addViewEvent.getView());
		} else if (event instanceof RemoveViewEvent) {
			RemoveViewEvent removeViewEvent = (RemoveViewEvent) event;
			removeView(removeViewEvent.getView());
		}
		
		
		handleEventImpl(event);
	}
	
	/**
	 * repräsentiert die HmvcListener.handleEvent() Methode
	 */
	public abstract void handleEventImpl(HmvcEvent event);
	
	/**
	 * entfernt die View von der RootPanel
	 * @param view
	 */
	private void removeView(View view) {
		if (RootPanel.get().remove(view.getWidget())) {
			view.setVisible(false);
		}
	}
	
	/**
	 * fügt die View zum RootPanel hinzu
	 * @param view
	 */
	private void addView(View view) {
		
		if (view.getWidget() == null) {
			return;
		}
		
		view.setVisible(true);
		RootPanel.get().add(view.getWidget());
	}
	
	/**
	 * Entry-Point
	 */
	public void onModuleLoad() {
		new Triad(this);
	}
	
}
